// client.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
using namespace std;

#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/bind.hpp>
using namespace boost::asio;
using namespace boost;

class a_timer
{
public:
  template<typename F> a_timer(io_service& ios, int x, F func)
    : f(func), count_max(x), count(0), t(ios, posix_time::milliseconds(500))
  {
    t.async_wait(bind(&a_timer::call_func, this, placeholders::error));
  }

  void call_func(const system::error_code&)
  {
    if(count >= count_max)
      return;

    ++count;
    f();
    t.expires_at(t.expires_at()+posix_time::milliseconds(500));
    t.async_wait(bind(&a_timer::call_func, this, placeholders::error));
  }
protected:
private:
  int count;
  int count_max;
  function<void()> f;
  deadline_timer t;
};

void client(io_service& ios)
{
  try
  {
    cout << "client start." << endl;
    ip::tcp::socket sock(ios);
    ip::tcp::endpoint ep(ip::address::from_string("127.0.0.1"), 6688);
    sock.connect(ep);

    vector<char> str(100, 0);
    sock.read_some(buffer(str));
    cout << "recive from " << sock.remote_endpoint().address();
    cout << &str[0] << endl;
  }
  catch(...)
  {

  }
}

int _tmain(int argc, _TCHAR* argv[])
{
  io_service ios;
  a_timer at(ios, 5, bind(client, ref(ios)));
  ios.run();

  getchar();

	return 0;
}

